package net.atomarrow.util;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author boolone
 * @date 2021-12-26 10:48
 */
public class EnumUtil {

	/**
	 * 将枚举类的常量提取出来作为选项，key就是常量名，value是指定的属性值
	 * @param enumClass
	 * @param valueColumn
	 * @param <E>
	 * @return
	 */
	public static <E extends Enum<E>> Map<String, Object> listAsOptions(Class<E> enumClass, String valueColumn) {
		if (enumClass == null || enumClass.isEnum() == false) {
			throw new RuntimeException("非枚举类，无法使用该方法");
		}
		E[] constants = enumClass.getEnumConstants();
		if(constants.length > 0) {
			HashMap<String, Object> map = new HashMap<>();
			for (E constant : constants) {
				map.put(constant.toString(), BeanUtil.getValue(valueColumn, constant));
			}
			return map;
		}

		return Collections.emptyMap();
	}

	/**
	 * 根据名称，返回枚举类中对应的常量
	 * @param enumClass
	 * @param name
	 * @param <E>
	 * @return
	 */
	public static <E> E getValueByName(Class<E> enumClass, String name) {
		if (enumClass == null || enumClass.isEnum() == false) {
			throw new RuntimeException("非枚举类，无法使用该方法");
		}
		try {
			return (E) enumClass.getMethod("valueOf", String.class).invoke(enumClass, name);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
